
from  common  import *
import sys, socket, time, os, subprocess, Queue
from subprocess import * 
from lib.ThreadGetKey import *


NORMAL = 0  
ERROR = 1  
TIMEOUT = 5  

class ThreadGetKey(threading.Thread):
    def run(self):
        try:           
            chr = msvcrt.getch()
            if chr == 'q':
                print "stopped by your action ( q )"
                os._exit(1)
        except:
            os._exit(1) 
 

def ping(ip , port , timeout=10):  
     return 1
     try:  
         cs = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  
         cs.settimeout(float(timeout))  
         address = (str(ip), int(port))  
         status = cs.connect_ex((address))  
         if status == NORMAL :  
             return 1;
     except Exception , e:  
         print ERROR  
         print "error:%s" % e  
         return ERROR  
     cs.close()  
     return 0      
    
    
def rsync(file):
    global host_list
    host_list = Queue.Queue()
    for host in open(file, 'r'):
      host_list.put(host.strip())
    l = host_list.qsize()
    threads = []
    if l > 0 :
        msg("Pentest %d hosts" % l)
        hander = ThreadGetKey()
        hander.setDaemon(True)
        hander.start()
        for i in range(20):
          a = RsyncCarck("xx")
          a.start()
          threads.append(a)
        for j in threads:
          j.join()
    else :
        msg("No Hosts")
  

class RsyncCarck(threading.Thread):
    def __init__(self, host):
        threading.Thread.__init__(self)
        self.host = host
    
    def run(self):
      while 1:
         if host_list.empty() == True:
             break
             os.exit()
         time.sleep(1)
         host = str(host_list.get())
         msg("Pentest "+host+" rsync") 
         if ping(host, 873):
          msg("Rsync server running", 1)
          rsync_client = "bin\\rsync.exe  ";  # rsync client path
          pipe = os.popen(rsync_client + host + "::")
          msg_text = pipe.read()
          pipe.close()
          msg_arr=[]
          if msg_text :
            msg_arr = msg_text.split('\n')
          if len(msg_arr) > 0:
             msg("%d modules Found" % len(msg_arr), 1)
             for module in msg_arr :
               if module :
                msg("Test %s::%s" % (host,module));
                module = module.strip()
                p = Popen(rsync_client + host + "::" + module, stdin=PIPE, stdout=PIPE)  
                req = p.stdout.readline()
                if req and len(req and "@ERROR") :
                  msg("Anonymous rsync module:" + module + " found !!!", 1)
                else :
                  print req
               else :
                 continue
          else :
            msg("No modules Found", 2)
               
        
        
        
        
        
